package cn.edu.scut.sys.dao.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.hibernate.sql.JoinType;
import org.springframework.stereotype.Component;
import cn.edu.scut.sys.dao.TrainScoreItemDao;
import cn.edu.scut.sys.utils.StringUtils;
import cn.edu.scut.sys.vo.TrainScoreItem;

@Component("trainScoreItemDao")
public class TrainScoreItemDaoImpl implements TrainScoreItemDao{

	private SessionFactory sessionFactory;

	@Resource(name="sessionFactory")
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Override
	public Long count() {
		String hql = "select count(id) from TrainScoreItem";
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		return Long.valueOf(query.uniqueResult().toString());
	}

	@Override
	public List<TrainScoreItem> list(int start, int limit, String sort, String sidx,long trainScoreId) {
		Criteria criteria = sessionFactory.getCurrentSession().createCriteria(TrainScoreItem.class);
		criteria.createAlias("trainScore", "trainScore", JoinType.LEFT_OUTER_JOIN);
		criteria.createAlias("trainItem", "trainItem", JoinType.LEFT_OUTER_JOIN);
		criteria.add(Restrictions.eq("trainScore.id", trainScoreId));
		criteria.setFirstResult(start).setMaxResults(limit);
		if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(sidx)){
			if ("desc".equals(sort)){
				criteria.addOrder(Order.desc(sidx));
			} else if ("asc".equals(sort)){
				criteria.addOrder(Order.asc(sidx));
			}
		}
		
		return criteria.list(); 
	}

	@Override
	public void insert(TrainScoreItem trainScoreItem) {
		sessionFactory.getCurrentSession().save(trainScoreItem);
		sessionFactory.getCurrentSession().flush();
		sessionFactory.getCurrentSession().clear();
	}

	@Override
	public TrainScoreItem get(Long id) {
		return (TrainScoreItem)sessionFactory.getCurrentSession().load(TrainScoreItem.class, id);
	}

	@Override
	public void update(TrainScoreItem trainScoreItem) {
		sessionFactory.getCurrentSession().update(trainScoreItem);
		sessionFactory.getCurrentSession().flush();
		sessionFactory.getCurrentSession().clear();
	}
	
	
}
